package com.kingbook.core.scripting.nodes;

import com.kingbook.common.utils.StringUtils;
import com.kingbook.core.sql.dialect.DBDialect;
import org.jdom2.Content;
import org.jdom2.Element;
import org.jdom2.Text;

import java.util.List;
import java.util.Map;

/**
 * @Author: Bucky
 * @Date: 2019/1/2
 * @Version 1.0
 */
public interface Node {

    default String getSql(Map<String, ?> paramMap, Map<String, SegmentNode> segMap) {
        return "";
    }

    default String getSql(List<Node> nodeList, Map<String, ?> paramMap, Map<String, SegmentNode> segMap) {
        StringBuilder sb = new StringBuilder();
        nodeList.forEach(h -> {
            sb.append(h.getSql(paramMap, segMap)).append(" ");
        });
        return sb.toString();
    }

    default void resolve(List<Node> nodeList, Element element) {
        for (Content el : element.getContent()) {
            if (el instanceof Element) {
                Element de = (Element) el;
                if ("include".equals(de.getName())) {
                    nodeList.add(new IncludeNode(de));
                } else if ("when".equals(de.getName())) {
                    nodeList.add(new WhenNode(de));
                } else if ("trim".equals(de.getName())) {
                    nodeList.add(new TrimNode(de));
                } else if ("where".equals(de.getName())) {
                    nodeList.add(new WhereNode(de));
                } else if ("set".equals(de.getName())) {
                    nodeList.add(new SetNode(de));
                }
            } else if (el instanceof Text) {
                String text = replaceTab(((Text) el).getTextTrim());
                if (StringUtils.isNotEmpty(text)) {
                    nodeList.add(new Node() {
                        @Override
                        public String getSql(Map<String, ?> map, Map<String, SegmentNode> segMap) {
                            return text;
                        }
                    });
                }
            }
        }
    }


    default String replaceTab(String str) {
        String[] ss = str.split(" ");
        String tt = "";
        for (String s : ss) {
            if (StringUtils.isNotEmpty(s))
                tt += s.trim() + " ";
        }
        return tt.trim();
    }
}
